package org.codingq92.frame.spring.config;

import lombok.Getter;
import org.codingq92.frame.spring.ann.CusAutowired;
import org.codingq92.frame.spring.ann.CusComponent;
import org.codingq92.frame.spring.ann.CusPostConstruct;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Getter
public class BeanDefinition {

    private final String name;
    private final Class<?> beanType;
    private final List<Field> autowiredFields;
    private final Constructor<?> constructor;
    private final Method postConstructMethod;

    public BeanDefinition(Class<?> clazz) {
        this.beanType = clazz;
        CusComponent clazzAnnotation = clazz.getAnnotation(CusComponent.class);
        // bean没有在注解上写名字就默认类名字
        this.name = clazzAnnotation.name().isEmpty() ? clazz.getSimpleName() : clazzAnnotation.name();
        try {
            // 默认的无参构造
            this.constructor = clazz.getConstructor();
            // 获取bean的属性 CusAutowired注解
            this.autowiredFields = Arrays.stream(clazz.getDeclaredFields())
                    .filter(method -> method.isAnnotationPresent(CusAutowired.class))
                    .toList();
            // 获取CusPostConstruct注解方法并保存
            this.postConstructMethod = Arrays.stream(clazz.getDeclaredMethods())
                    .filter(method -> method.isAnnotationPresent(CusPostConstruct.class))
                    .findFirst().orElse(null); // 获取CusPostConstruct 这里只获取一个!!!也可以获取多个的!!!
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}
